//
//  LGHomeSearcjViewController.m
//  LuxuryGoods
//
//  Created by 纳里健康 on 2018/5/28.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "LGHomeSearcjViewController.h"
#import "LGTagTableViewCell.h"
#import "LGSearchResultViewController.h"


#import "NDPageConfig.h"
#import "NDPageViewController.h"
#import "LGResultListViewController.h"
#import "LGSearchModel.h"
#import "LGKeywordModel.h"
#import "LGScreenViewController.h"

NSString * const kSearchHistory = @"kSearchHistory";

@interface LGHomeSearcjViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,TagCellDelegate,NDPageViewControllerDelegate>
{
    UITableView *_tableView;
    
    NSMutableArray *_historyArray;
    
    NSMutableArray *_recommendArray;
    
    NSMutableArray *_tableDataArray;
    
    CGFloat _cellHeight;
    
    UISearchBar *_searchBar;
    
    NSMutableArray *_ViewControllersArray;
    
    NDPageConfig *_config;
    
    LGSearchModel *_searchModel;
    
    NSString *_searchKeyword;
    
    

}

@end

@implementation LGHomeSearcjViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self makeNavBar];
    
//    _historyArray = @[@"哈哈哈哈哈哈", @"哈试发",@"哈你发",@"哈哈试会计给你发",@"哈哈你发",@"哈哈哈哈哈发", @"哈哈哈哈哈哈考试会计给你发"].mutableCopy;
    
    [self getHistoryOrRecommentArray];
    
    [self maketableView];
}

- (void)getHistoryOrRecommentArray
{
    [[MainApi sharedInstance] getPath:@"Index/searchInfo" params:nil resultBlock:^(NSDictionary *responseObject, NSError *error) {
        NSInteger code = [responseObject[@"code"] integerValue];
        
        if(code == 1)
        {
            NSDictionary *dict = responseObject[@"data"];
            
            self->_searchModel = [LGSearchModel yy_modelWithJSON:dict];
            
            [self makeData];
        }
        
    }];
}

- (void)addSearchKey:(NSString *)key{
    __block NSInteger index = -1;
    [_historyArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([key isEqualToString:obj]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index == -1) {
        [_historyArray insertObject:key atIndex:0];
    }else{
        [_historyArray exchangeObjectAtIndex:0 withObjectAtIndex:index];
    }
    //最多15条记录
    if (_historyArray.count > 15) {
        [_historyArray removeObjectsInRange:NSMakeRange(15, _historyArray.count-15)];
    }
    [[NSUserDefaults standardUserDefaults] setObject:_historyArray forKey:kSearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)makeData
{
    //获取历史记录
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *tmpArray = [userDefaults arrayForKey:kSearchHistory];
    _historyArray = [NSMutableArray arrayWithArray:tmpArray];
    
    //热门搜索
    _recommendArray = [NSMutableArray arrayWithCapacity:_searchModel.hot_keywords.count];
    
    _tableDataArray = [NSMutableArray array];
    
    NSArray *keywoedArray = _searchModel.hot_keywords;
    
    for (LGKeywordModel *model in keywoedArray) {
        [_recommendArray addObject: model.keywords];
    }
    
    
    if(_historyArray.count > 0)
    {
        NSDictionary *dict1 = @{
                                @"title":@"历史记录",
                                @"canDelete":@(YES),
                                @"tagArray":_historyArray
                                };
        
        [_tableDataArray addObject:dict1];
    }
    
    if(_recommendArray.count > 0)
    {
        NSDictionary *dict2 = @{
                                @"title":@"热门搜索",
                                @"canDelete":@(NO),
                                @"tagArray":_recommendArray
                                };
        
        [_tableDataArray addObject:dict2];
    }
    
    [_tableView reloadData];
}


- (void)maketableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATOR_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = BACKGROUND_COLOR;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
}

- (void)makeNavBar
{
    UIView  *titleView = [[UIView alloc] initWithFrame:CGRectMake(50, 7, SCREEN_WIDTH - 50 - 15, 30)];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 50 - 15, 30)];
    
    _searchBar.placeholder = @"请输入商品名称";
    
    _searchBar.backgroundImage = [[UIImage alloc] init];
    // 设置SearchBar的颜色主题为白色
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.delegate = self;
    
    UITextField *searchField = [_searchBar valueForKey:@"searchField"];
    if (searchField) {
        [searchField setBackgroundColor:UIColorFromRGB(0xEEEEEE)];
        searchField.layer.cornerRadius = 16.0f;
        searchField.font = [UIFont systemFontOfSize:14];
        searchField.layer.masksToBounds = YES;
    }
    
    [titleView addSubview:_searchBar];
    self.navigationItem.titleView = titleView;
}

#pragma mark -- tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _tableDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier =  @"LGTagTableViewCell";
    
    LGTagTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if(cell == nil)
    {
        cell = [[NSBundle mainBundle] loadNibNamed:@"LGTagTableViewCell" owner:self options:nil][0];
    }
    
    [cell setTagCellWithDict:_tableDataArray[indexPath.section]];
    
    cell.delegate = self;
    
    _cellHeight = cell.cellHeight;
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
   if(section == 1)
   {
       return 5.0f;
   }
    
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] init];
    header.backgroundColor = BACKGROUND_COLOR;
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}


#pragma mark -- searchBar按钮点击
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"开始搜索");
    
    [searchBar resignFirstResponder];
    
    _searchKeyword = searchBar.text;
    [self addSearchKey:_searchKeyword];
    [self makeMenu];
    
}

#pragma mark -- 标签点击代理
- (void)clickTagText:(NSString *)tagString
{
    _searchBar.text = tagString;
    
    [_searchBar resignFirstResponder];
    
    _searchKeyword = tagString;
    [self addSearchKey:_searchKeyword];
    [self makeMenu];
}
#pragma mark -- 点击删除按钮，清除历史记录
- (void)clickDeleteBtn{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除全部搜索记录吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self->_historyArray removeAllObjects];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:kSearchHistory];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self makeData];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
    [self presentViewController:alert animated:YES completion:NULL];
}


-(void)makeMenu
{
    _config = [[NDPageConfig alloc]init];
    _config.barBtnWidth = SCREEN_WIDTH/4;
    _config.barViewH = 40;
    _config.nomalColor = TEXT_COLOR_2;
    _config.selectColor = TOPCAIL_COLOR;
    _config.nomalFont = [UIFont systemFontOfSize:15];
    _config.selectFont = [UIFont systemFontOfSize:15];
    _config.lineWidth = SCREEN_WIDTH/4;
    _config.lineHight = 0;
    _config.lineColor = TOPCAIL_COLOR;
    
    _config.showIndentifier = YES;
    _config.backColor = WHITE_COLOR;
    
    _ViewControllersArray = @[].mutableCopy;
    
    for (int i = 0; i < 4; i ++) {
        
        LGResultListViewController *resultVC = [[LGResultListViewController alloc] init];
        
        resultVC.Type = (searchType)i;
        resultVC.fromType = typeSearch;
        
        resultVC.keyWords = _searchKeyword;
        
        resultVC.index = i;
        [_ViewControllersArray addObject:resultVC];
    }
    
    //综合 价格  上新  筛选
    NDPageViewController *pageViewController = [[NDPageViewController alloc]initWithClassArray:_ViewControllersArray titleArray:@[@"综合",@"价格",@"上新",@"筛选"] config:_config];
    
    pageViewController.delegate = self;
    
    [self addChildViewController:pageViewController];
    pageViewController.view.frame = self.view.bounds;
    [self.view addSubview:pageViewController.view];
}

-(void)pageViewOpenMenuAtIndex:(NSInteger)index
{
    if(index == 1)
    {   //当menu为价格的时候，点击刷新数据
        LGResultListViewController *resultVC = _ViewControllersArray[index];
        resultVC.Type = priceDowmType;
        [resultVC requestData];
    }else if(index == 2)
    {
        LGResultListViewController *resultVC = _ViewControllersArray[index];
        resultVC.Type = priceDowmType;
        [resultVC requestData];
    }
}

-(void)pageViewCloseMenuAtIndex:(NSInteger)index
{
    if(index == 1)
    {
        LGResultListViewController *resultVC = _ViewControllersArray[index];
        resultVC.Type = priceupType;
        [resultVC requestData];
    }else if(index == 2)
    {
        LGResultListViewController *resultVC = _ViewControllersArray[index];
        resultVC.Type = priceDowmType;
        [resultVC requestData];
    }
}

-(void)pageViewSelectAtIndex:(NSInteger)index
{
    NSLog(@"------- %ld",(long)index);
    
    if(index == 1)
    {
        _config.openImage = [UIImage imageNamed:@"Down"];
        _config.closeImage = [UIImage imageNamed:@"Up"];//
        
    }else if (index == 2)
    {
        _config.openImage = [UIImage imageNamed:@"Down"];
        _config.closeImage = [UIImage imageNamed:@"Up"];
    }
    else
    {
        
        _config.openImage = [UIImage imageNamed:@""];
        _config.closeImage = [UIImage imageNamed:@""];
    }
    
    if(index == 3)
    {
        LGScreenViewController *screenView = [[LGScreenViewController alloc] init];
        
        screenView.view.frame = self.view.bounds;
        
        [self.view addSubview:screenView.view];
    }

    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
